package org.shj.service;

import java.util.Date;
import java.util.List;

import org.shj.db.DbConnect;
import org.shj.entity.User;
import org.shj.util.StringUtils;

public class UserServiceImpl implements UserService{
	
	private DbConnect dbConnect = DbConnect.getInstance();

	public boolean isValidUser(String userId, String password){
		if(StringUtils.isEmpty(userId) || StringUtils.isEmpty(password)){
			return false;
		}
		User user = getUserById(userId);
		if(user == null){
			return false;
		}
		String pwd = StringUtils.toMD5Hex(password);
		return pwd.equalsIgnoreCase(user.getPassword());
	}
	
	public User getUserById(String userId){
		String sql = "select * from tbl_user where user_id = ?";
		List<User> users = dbConnect.getResultsBySql(sql, User.class, userId);
		if(users == null || users.isEmpty()){
			return null;
		}else{
			return users.get(0);
		}
	}

	@Override
	public boolean saveUser(User user) {
		String sql = "insert into tbl_user (user_id, username, password, created_time) values (?, ?, ?, ?)";
		return this.dbConnect.update(sql, user.getUserId(), user.getUsername(), 
				StringUtils.toMD5Hex(user.getPassword()), new Date());
	}
}
